<script>
import { ref } from 'vue';
import http from '@/utils/api.js'
import router from "@/router/index.js"
import { ElMessage } from 'element-plus';

export default {
  setup() {
    const email = ref('');
    const username = ref('');
    const password = ref('');
    const confirmPassword = ref('');

    // 默认错误提示
    const emailError = ref('');
    const usernameError = ref('');
    const passwordError = ref('');
    const confirmPasswordError = ref('');

    // 校验规则
    const validateEmail = () => {
      const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zAZ]{2,}$/;
      emailError.value = email.value ?
          (emailRegex.test(email.value) ? '' : '邮箱格式不正确') : '不能为空';
    };

    const validateUsername = () => {
      usernameError.value = username.value ?
          (username.value.length >= 3 ? '' : '用户名长度至少为 3 个字符') : '不能为空';
    };

    const validatePassword = () => {
      passwordError.value = password.value ?
          (password.value.length >= 6 ? '' : '密码长度至少为 6 个字符') : '不能为空';
    };
    const validateConfirmPassword = () => {
      confirmPasswordError.value = password.value ?
          (confirmPassword.value === password.value ? '' : '两次密码不一致') : '不能为空';
    };

    // 注册处理函数
    const handleRegister = async () => {
      // 校验输入
      validateEmail();
      validateUsername();
      validatePassword();
      validateConfirmPassword();

      // 如果有任何错误，阻止提交
      if (emailError.value || usernameError.value || passwordError.value || confirmPasswordError.value) {
        return;
      }

      try {
        // 发送请求注册
        const response = await http.post("/user/register", {
          email: email.value,
          username: username.value,
          password: password.value
        });

        if (response.code === 200 && response.message.toLowerCase().includes("成功")) {
          alert("注册成功！");
          localStorage.setItem('userToken', response.accessToken);
          await router.push('/login');  // 跳转到登录页面
        } else {
          alert(`注册失败: ${response.message}`);
          console.error("Registration failed with message:", response.message);
        }
      } catch (err) {
        console.error(err);
        alert("注册时发生错误，请稍后再试！");
      }
    };

    return {
      email,
      username,
      password,
      emailError,
      usernameError,
      passwordError,
      handleRegister,
      validateEmail,
      validateUsername,
      validatePassword,
      confirmPassword,
      confirmPasswordError,
      validateConfirmPassword,
    };
  }
}
</script>

<template>
  <div style="display: flex; align-items: center; justify-content: center; height: 100vh;">
    <div
        style="background-color: white; padding: 40px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); max-width: 400px; width: 100%;"
    >
      <h1
          style="text-align: center; color: #d81b60; font-size: 24px; margin-bottom: 20px;"
      >
        注册
      </h1>
      <p
          style="text-align: center; color: #666; font-size: 14px; margin-bottom: 20px;"
      >
        每一次注册都是与你的相遇。
      </p>
      <form style="display: flex; flex-direction: column;" @submit.prevent>
        <!-- 邮箱输入框 -->
        <div class="input-container">
          <input
              type="email"
              v-model="email"
              placeholder="邮箱"
              @blur="validateEmail"
          />
          <div v-show="emailError" class="error-message">
            {{ emailError }}
          </div>
        </div>

        <!-- 用户名输入框 -->
        <div class="input-container">
          <input
              type="text"
              v-model="username"
              placeholder="用户名"
              @blur="validateUsername"
          />
          <div v-show="usernameError" class="error-message">
            {{ usernameError }}
          </div>
        </div>

        <!-- 密码输入框 -->
        <div class="input-container">
          <input
              type="password"
              v-model="password"
              placeholder="密码"
              @blur="validatePassword"
          />
          <div v-show="passwordError" class="error-message">
            {{ passwordError }}
          </div>
        </div>
<!--        确认密码-->
        <div class="input-container">
          <input
              type="password"
              v-model="confirmPassword"
              placeholder="确认密码"
              @blur="validateConfirmPassword"
          />
          <div v-show="confirmPasswordError" class="error-message">
            {{ confirmPasswordError }}
          </div>
        </div>
        <button
            type="button"
            @click="handleRegister"
            style="margin-top: 10px;"
        >
          注册
        </button>
      </form>
    </div>
  </div>
</template>

<style scoped>
/* 页面整体样式 */
.input-container {
  position: relative; /* 使错误信息可以绝对定位在输入框下方 */
  margin-bottom: 28px; /* 增加输入框之间的间距 */
}
form{
  width: 280px;
}

input {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 16px;
  width: 100%;
}

button {
  background-color: #d81b60;
  color: white;
  padding: 10px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  width: 100%;
}

/* 错误提示样式 */
.error-message {
  position: absolute; /* 绝对定位，使其显示在输入框下方 */
  color: red;
  font-size: 12px;
  margin-top: 5px; /* 增加提示框上方的间距，确保不重叠 */
  left: 0;
  width: 100%;
}

form {
  display: flex;
  flex-direction: column;
}

form input {
  margin-bottom: 10px;
}

form button {
  margin-top: 20px;
}
</style>
